package com.acme.bankapp.service.email;

import com.acme.bankapp.domain.email.Email;
import com.acme.bankapp.domain.email.Queue;
import com.acme.bankapp.domain.email.impl.EmailImpl;
import com.acme.bankapp.domain.email.impl.QueueImpl;
import com.acme.bankapp.domain.exceptions.EmptyEmailBoxException;
import com.acme.bankapp.domain.exceptions.MailCantBeAdded;

public class EmailService implements Runnable {

	private Queue queue;
	
	private static EmailService instance = new EmailService();
	
	public EmailService() {
		queue = new QueueImpl(10);
		//make a new thread for emailService
				
		Thread t = new Thread(instance);
		t.start();
	}

	public static EmailService getEmailService() {
		return instance;
	}
	
	public void sendNotificationEmail (Email email) {
		try {
			queue.addEmail(email);
		} catch (MailCantBeAdded e) {
			System.out.println("can't send a mail");
		}
	}

	public void close() {
		queue.close();		
	}

	@Override
	public void run() { //trying to get email from Queue and "send" it		
		System.out.println("in run " + queue.isClosed());
		while(!queue.isClosed()){
			try {
				System.out.println("before getEmail");
				Email email = queue.getEmail();
				System.out.println("after getEmail");
				System.out.println(email.toString());
			} catch (EmptyEmailBoxException e) {
				System.out.println("mail box is empty");
				break;
			}
		}
	}
}
